<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .bx {
            max-width: 60%;
            margin: auto;
            display: flex;
        }

        .sm {
            width: 350px;
            height: 350px;
            position: relative;
        }

        .sm img {
            width: 100%;
            display: block;
        }

        .mask {
            width: 150px;
            height: 150px;
            background-color: #fbfb0b4d;
            position: absolute;
            display: none;
        }

        canvas {
            display: none;
        }
    </style>
</head>

<body>
    <div class="bx">
        <div class="sm">
            <img src="./images/jd/1a154d56822e0ae9.jpg.avif" alt="">
            <div class="mask"></div>
        </div>
        <canvas id="cvs" width="350" height="350"></canvas>
    </div>
    <script>
        var sm = document.querySelector('.sm');
        var mask = document.querySelector('.mask');



        var cvs = document.getElementById('cvs')
        var ctx = cvs.getContext('2d');
        var img = document.querySelector('.sm img')
        var fixedH = 0, fixedW = 0;
        img.onload = function () {
            fixedH = img.naturalHeight;
            fixedW = img.naturalWidth;
        }
        sm.addEventListener('mousemove', function (event) {
            var { pageX, pageY } = event;
            var maxX = sm.offsetWidth - mask.offsetWidth;
            var maxY = sm.offsetHeight - mask.offsetHeight;
            let y = pageY - sm.offsetTop - mask.offsetHeight / 2;
            let x = pageX - sm.offsetLeft - mask.offsetWidth / 2;
            x = x < 0 ? 0 : x;
            y = y < 0 ? 0 : y;

            x = x > maxX ? maxX : x;
            y = y > maxY ? maxY : y;
            mask.style.top = y + 'px';
            mask.style.left = x + 'px';

            ctx.clearRect(0, 0, 350, 350);
            var sx = x / 350 * fixedW;
            var sy = y / 350 * fixedH;
            var sw = 150 * fixedW / 350;
            var sh = 150 * fixedH / 350;
            ctx.drawImage(img, sx, sy, sw, sh, 0, 0, 350, 350);
        })
        sm.addEventListener('mouseenter', function () {
            cvs.style.display = 'block';
            mask.style.display = 'block';
        })
        sm.addEventListener('mouseleave', function () {
            cvs.style.display = '';
            mask.style.display = '';
        })
    </script>
</body>

</html>